<template>
  <div class="app-container">
    <el-form v-if="showAssort">
      <template v-for="assort in assortInfo.assortList" >
        <el-form-item v-if="assort.options" :label="assort.label" label-width="80px" :prop="assort.attrId" >
          <el-radio-group v-if="assort.options && assort.options.length > 0" v-model="assort.value"
                          size="mini" @change="handelRedioChange(assort.attrId)" >
            <el-tooltip effect="dark" v-for="item in assort.options" :content="item.tooltip_text" placement="top">
              <el-radio-button :class="item.cssClass" :label="item.value" :disabled="item.disabled" >{{ item.label }}</el-radio-button>
            </el-tooltip>
          </el-radio-group>
        </el-form-item>
      </template>
      <el-button id="refresh-btn" type="primary" plain round size='mini' @click="refresh" >刷新</el-button>
      <el-button id="refresh-btn" type="success" plain round size='mini' @click="handleAdd" v-hasPermi="['goods:main:add']" >新增</el-button>
    </el-form>

    <el-divider content-position="center">
      <i class="el-icon-caret-top" v-if="showAssort" @click="handleTriggerAssort"></i>
      <i class="el-icon-caret-bottom" v-else @click="handleTriggerAssort"></i>
    </el-divider>
    <el-row>
      <el-col :span="18">
        <el-descriptions title="商品信息" :column="3" size="small" border>
          <el-descriptions-item label="商品编码">{{ mainInfo.gNumber }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ mainInfo.goodsName }}</el-descriptions-item>
          <el-descriptions-item label="创建者">  {{ mainInfo.createBy }}</el-descriptions-item>
          <el-descriptions-item label="商品品牌">{{ mainInfo.brandName }}</el-descriptions-item>
          <el-descriptions-item label="商品类型">{{ mainInfo.typeName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ mainInfo.createTime }}</el-descriptions-item>
          <el-descriptions-item label="关联商品">{{ mainInfo.assNumber }}</el-descriptions-item>
<!--          <el-descriptions-item label="状态">-->
<!--            <dict-tag :options="dict.type.sys_goods_sj_status" :value="mainInfo.status"/>-->
<!--          </el-descriptions-item>-->
          <el-descriptions-item label="价格">{{ mainInfo.price/100 }}￥</el-descriptions-item>
          <el-descriptions-item label="修改者">  {{ mainInfo.updateBy }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ mainInfo.remark }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ mainInfo.updateTime }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col :span="6" style="padding-top: 41px;">
        <el-card class="cover-image-card" :body-style="{ padding: '0px', width: '200px', height: '200px' }">
          <div style="width: 200px; height: 200px;">
            <el-image :src="mainInfo.image" :preview-src-list="coverPreviewList" style="width: 200px; height: 200px;" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-collapse v-model="activeNames">
      <el-collapse-item name="config">
        <template slot="title">
          <div style="display: flex; justify-content: space-between; width: 100%;">
            <div>
              <span>商品属性信息</span>
            </div>
            <div style="float: right; margin-right: 10px;">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop.prevent="handleEdit('config')"
                v-hasPermi="['goods:config:edit']"
              >编辑</el-button>
            </div>
          </div>
        </template>
        <el-descriptions :column="4" size="small" border>
          <el-descriptions-item
            v-for="item in configInfo"
            :label="item.attrName"
          >
            {{ item.configVal || (item.valueUnit ? item.valueName+' '+item.valueUnit : item.valueName) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-collapse-item>
      <el-collapse-item title="商品图片" name="img">
        <template slot="title">
          <div style="display: flex; justify-content: space-between; width: 100%;">
            <div>
              <span>商品图片信息</span>
            </div>
            <div style="float: right; margin-right: 10px;">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop.prevent="handleEdit('image')"
                v-hasPermi="['goods:image:edit']"
              >编辑</el-button>
            </div>
          </div>
        </template>
        <el-carousel v-if="carouselList && carouselList.length > 0" :interval="5000" type="card" height="400px">
          <el-carousel-item v-for="item in carouselList" :key="item">
            <el-image :src="item" />
          </el-carousel-item>
        </el-carousel>
        <div v-if="descImageList" style="width: 600px; margin-left: 30px">
          <el-image v-for="item in descImageList" :src="item" fit="contain" style="width: 600px; height: auto;" />
        </div>
      </el-collapse-item>
      <el-collapse-item title="商品详情" name="desc" >
        <template slot="title">
          <div style="display: flex; justify-content: space-between; width: 100%;">
            <div>
              <span>商品售后信息</span>
            </div>
            <div style="float: right; margin-right: 10px;">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop.prevent="handleEdit('desc')"
                v-hasPermi="['goods:config:edit']"
              >编辑</el-button>
            </div>
          </div>
        </template>
        <div v-if="descInfo" v-html="descInfo.content"></div>
      </el-collapse-item>
    </el-collapse>

    <main-add ref="mainAdd" :params="{ 'gNumber': gNumber }" @success="handleAddSuccess"  />

  </div>
</template>
<script>
import { getMainByGNumber, getAssortInfo } from "@/api/goods/main";
import { listConfig } from "@/api/goods/config";
import { getImagesByGNumber } from "@/api/goods/image";
import { listDesc } from "@/api/goods/desc";


import MainAdd from '@/views/goods/main/add.vue'
import ImageSelect from '@/views/goods/images/components/selectImage.vue'

export default {
  name: "GoodsInfo",
  dicts: ['sys_normal_disable', 'sys_goods_sj_status', 'sys_yes_no'],
  components: { ImageSelect, MainAdd },
  data() {
    return {
      imgServe: process.env.VUE_APP_BASE_API,
      showAssort: true,
      gNumber: null,
      goodsId: null,
      mainInfo: {},
      configInfo: [],
      imagesInfo: [],
      descInfo: {},
      srcList: [],
      carouselList: [],
      descImageList: [],
      coverPreviewList: [],
      // activeNames: [ 'config' ],
      activeNames: [ 'config', 'img', 'desc' ],
      // 弹出层信息
      dialogInfo: {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 展示模式
        mode: "",
        // 数据
        configList: [],
      },
      // 表单数据
      form: {},
      assortInfo: {
        assort: {},
        assortList: [],
      },
      labelPosition: 'right',
    }
  },
  created() {
    const gNumber = this.$route.params && this.$route.params.gNumber;
    this.gNumber = gNumber;
    this.getMain(gNumber);
    this.getAssortInfo();
  },
  methods: {
    refresh() {
      this.getMain(this.gNumber);
      this.getAssortInfo();
    },
    async getMain(gNumber) {
      await getMainByGNumber(gNumber).then(res => {
        let data = res.data;
        if (data.image) {
          data.image = this.generateImagePath(data.image);
        }
        this.coverPreviewList = [];
        this.coverPreviewList.push(data.image);
        this.mainInfo = data;
      })
      await this.getConfig();
      await this.getImages();
      this.getDescInfo();
    },
    getDescInfo() {
      listDesc(this.gNumber).then(res => {
        const data = res.data;
        if (data) {
          this.descInfo = data[0]
        }
      })
    },
    getAssortInfo() {
      let gNumber = this.gNumber;
      getAssortInfo(gNumber).then(res => {
        let map = res.data;
        this.assortInfo.assort = map.assort;
        this.assortInfo.assortList = map.assortOptions;
        this.generateAssortInfo();
      })
    },
    generateAssortInfo() {
      let assort = this.assortInfo.assort;
      let list = this.assortInfo.assortList;
      list.filter(item => {
        item.options.filter(option => {
          if (option.goods) {
            this.isExistGoods(item.attrId, assort, option);
          } else {
            option.disabled = true;
            option.cssClass = "no_goods"
            option.tooltip_text = "无此商品"
            option.hasGoods = false;
          }
        })
      })
      this.assortInfo.assortList = list;
    },
    isExistGoods(attrId, assort, option) {
      if (assort[attrId] && assort[attrId].attrId && option.value == assort[attrId].valueId) {
        option.tooltip_text = option.label
        option.cssClass = ""
        option.hasGoods = true;
      } else {
        let isExist = false;
        for (let gNumber in option.goods) {
          if (gNumber == this.gNumber) {
            isExist = true;
          }
          if (!isExist) {
            isExist = true;
            let attrs = option.goods[gNumber];
            for (let attr in assort) {
              if (assort[attr] && assort[attr].attrId && assort[attr].attrId != attrId) {
                if (assort[attr].valueId != attrs[attr]) {
                  isExist = false;
                }
              }
            }
          }
        }
        if (isExist) {
          option.tooltip_text = option.label
          option.cssClass = ""
          option.hasGoods = true;
        } else {
          option.tooltip_text = this.generateNotExistMsg(attrId, assort, option)
          option.cssClass = "no_goods"
          option.hasGoods = false;
        }
      }
    },
    generateNotExistMsg(attrId, assort, option) {
      let msg = '';
      let hasAttrId = false;
      for (let id in assort) {
        if (id == attrId) {
          hasAttrId = true;
          msg += ' - [' + option.value + ']'
        } else {
          msg += ' - ' + assort[id].valueId
        }
      }
      if (!hasAttrId) {
        msg += ' - [' + option.value + ']'
      }
      if (msg) {
        msg = msg.substring(3) + ' 无此商品'
      }
      return msg;
    },
    async getConfig() {
      const param = { 'gNumber': this.gNumber};
      listConfig(param).then(res => {
        this.configInfo = res.data;
      })
    },
    async getImages() {
      getImagesByGNumber(this.gNumber).then(res => {
        this.imagesInfo = res.data;
        let list = [];
        let carouselList = [];
        let descImageList = [];
        this.imagesInfo.forEach(i => {
          if (i.imgType === '2') {
            carouselList.push(this.generateImagePath(i.imgPath));
          } else if (i.imgType === '3') {
            descImageList.push(this.generateImagePath(i.imgPath));
          }
          list.push(this.generateImagePath(i.imgPath));
        })
        this.carouselList = carouselList;
        this.descImageList = descImageList;
        this.srcList = list;
      })
    },
    handleEdit(type) {
      const gNumber = this.gNumber;
      this.$router.push("/goods/info/edit/" + gNumber + '?type=' + type);
    },
    handelRedioChange(attrId) {
      console.log('handelRedioChange', attrId)
      let oldGnumber = this.gNumber;
      let newGNumber = null;
      let hasGoods = false;
      this.assortInfo.assortList.filter(item => {
        if (item.attrId == attrId) {
          item.options.filter(option => {
            if (option.value == item.value) {
              if (option.hasGoods) {
                hasGoods = option.hasGoods;
                this.assortInfo.assort[attrId].attrId = attrId;
                this.assortInfo.assort[attrId].valueId = item.value;
                this.assortInfo.assort[attrId].attrName = item.label;
              } else {
                let assort = this.assortInfo.assort;
                for (let attr in this.assortInfo.assort) {
                  if (attr == attrId) {
                    assort[attr] = {
                      attrId: attrId,
                      valueId: item.value,
                      attrName: item.label
                    }
                  } else {
                    assort[attr] = {}
                  }
                }
              }
              let bo = false;
              for (let gNumber in option.goods) {
                if (!bo) {
                  bo = true;
                  let assort = this.assortInfo.assort;
                  for (let attr in this.assortInfo.assort) {
                    if (assort[attr].valueId && option.goods[gNumber][attr] != assort[attr].valueId) {
                      bo = false;
                    }
                  }
                  if (bo) {
                    newGNumber = gNumber;
                  }
                }
              }
            }
          })
        }
      })
      if (!hasGoods) {
        this.assortInfo.assortList.filter(item => {
          if (item.attrId != attrId) {
            item.value = null
          }
        })
      }
      if (newGNumber && oldGnumber != newGNumber) {
        this.gNumber = newGNumber;
        this.getMain(newGNumber);
      }
      this.generateAssortInfo();
    },
    generateImagePath(imagePath) {
      if (imagePath && imagePath.indexOf('http') !== 0) {
        return this.imgServe + imagePath;
      }
      return imagePath;
    },
    handleAdd() {
      this.$refs.mainAdd.show();
    },
    handleAddSuccess(gNumber) {
      if (gNumber) {
        this.$router.push("/goods/info/edit/" + gNumber);
      }
    },
    handleTriggerAssort() {
      this.showAssort = !this.showAssort;
    },
  },
}
</script>

<style scoped>
.fiex-width {
  width: 200px;
}
::v-deep .el-descriptions {
  .el-descriptions-item__label {
    width: 100px;
  }
  .el-descriptions-item__content {
    width: 25vh;
  }
}
::v-deep .el-form {
  display: flex;
  flex-wrap: nowrap;

  /* .el-form-item__content {
      margin-left: 80px;
  } */
}
::v-deep .el-radio-group {
  .el-radio-button:not(.no_goods) span {
    font-weight: bold;
  }
  .el-radio-button.is-active span {
    background-color: transparent;
    color: #666;
    border-color: red;
    box-shadow: -1px 0 0 0 red;
  }
  .el-radio-button.no_goods span {
    color: #bfbfbf;
  }
}
.cover-image-card {
  display: flex;
  justify-content: space-around;
}
::v-deep .el-card__body {
  border: 2px solid #e6ebf5; /* 边框样式 */
  box-shadow: 5px 5px 10px #e6ebf5; /* 阴影样式 */
}
::v-deep .el-carousel {
  text-align: center;
}
::v-deep .el-carousel__button {
  height: 5px;
}
#refresh-btn {
  width: 80px;
  height: 36px;
  line-height: 26px;
  margin-left: 20px;
}
</style>
